//
//  MNDCreditorBottomRootViewController.m
//  minidai
//
//  Created by 谭谭伟 on 2017/5/31.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDCreditorBottomRootViewController.h"
#import "MNDFinaceDetailModel.h"
#import "MNDBottomContainerViewController.h"
#import "MNDFinanceDescribleViewController.h"
#import "MNDFinanceRecordViewController.h"
#import "MNDTenderInfoViewController.h"
#import "MNDTransferRecordViewController.h"
#import "MNDLoginUserModel.h"
#import "MNDFinanceViewController.h"
#import "MNDCreditorInvestViewController.h"

#import "MNDUserModel.h"

@interface MNDCreditorBottomRootViewController ()<UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate,DescribleViewControllerDelegate,RecordViewControllerDelegate,TenderInfoViewControllerDelegate,TransferRecordViewControllerDelegate>
/*! 指示器所在的容器 */
@property (weak, nonatomic) IBOutlet UIView *indicatorContainerView;
/*!选择器的item */
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *segmentButtons;
/*! 指示器 指示当前所选择的view */
@property (weak, nonatomic) IBOutlet UIView *indicatorView;
/*! 指示器的左边约束 */
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *indicatorLeadingConstraint;
//容器  需要在storyboard或者在viewWidLoad里设置pageViewController的transaction style为Scroll
@property (strong, nonatomic) MNDBottomContainerViewController *pageViewController;
//保存分页的数组
@property (strong, nonatomic) NSMutableArray *pageContentControllers;
//YES表示通过选择按钮切换页面，NO表示通过滑动切换页面
@property (assign, nonatomic) BOOL isManuallSegmentSelect;
@property (assign, nonatomic) BOOL isGotoRighPlace;
@property (assign, nonatomic) BOOL changedController;
@property (assign, nonatomic) BOOL userDraggingStartedTransitionInProgress;

@property (assign, nonatomic) NSInteger currentIndexController;
@property (assign, nonatomic) NSInteger nextIndexController;

@property (nonatomic,strong) MNDFinaceDetailModel *detaiModel;

@property (strong ,nonatomic) MNDFinanceDescribleViewController *describleVC;
@property (strong ,nonatomic) MNDFinanceRecordViewController *financeRecordVC;
@property (strong ,nonatomic) MNDTenderInfoViewController *tenderInfoVC;
@property (strong ,nonatomic) MNDTransferRecordViewController *transferRecordVC;
@property (weak, nonatomic) IBOutlet UIButton *investButton;

@property (nonatomic, copy) NSString *userPhone;

@property (nonatomic, strong) MNDUserModel *userModel;

@end

@implementation MNDCreditorBottomRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //让第一个item进来就是选择状态
    for (UIButton *btn in self.segmentButtons) {
        if (btn.tag == 100) {
            btn.selected = YES;
        }
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDetailModel:) name:@"senderDetailModel" object:nil];
    [self initialPageViewControllers];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if ([MNDLoginUserModel isUserLogin]) {
        
        [self loadUserInfo];
    }
}

- (void)getDetailModel:(NSNotification *)notification{
    self.detaiModel = [notification.object objectForKey:@"detailModel"];
    [self configContents];
    //    [self.tableView reloadData];
}

- (void)configContents {
    self.describleVC.brrowContent = self.detaiModel.borrow_content;
    self.describleVC.brrowImg = self.detaiModel.borrow_img;
    
    self.financeRecordVC.tender = self.detaiModel.tender;
    self.tenderInfoVC.creditor = self.detaiModel.creditor;
    self.transferRecordVC.transfer = self.detaiModel.transfer;
    if ([self.detaiModel.creditor_status isEqualToString:@"1"]) {
        self.investButton.enabled = YES;
        [self.investButton setBackgroundImage:[UIImage imageNamed:@"creditor_detail_normal"] forState:UIControlStateNormal];
    }else {
        self.investButton.enabled = NO;
        [self.investButton setBackgroundImage:nil forState:UIControlStateNormal];
        [self.investButton setBackgroundColor:[UIColor colorWithRed:181/255.0 green:181/255.0 blue:181/255.0 alpha:1.0]];
    }
}

#pragma mark -跳转到投资页
- (IBAction)goInvestAction:(UIButton *)sender {
    //未登录，先登录
    if (![MNDLoginUserModel isUserLogin]) {
        
        [self goToLoginVC];
        
        return;
    }
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:[NSBundle mainBundle]];
    MNDCreditorInvestViewController *creditorInvestVC = [storyboard instantiateViewControllerWithIdentifier:@"MNDCreditorInvestViewController"];
    creditorInvestVC.creditorCode = self.detaiModel.creditor_code;
    creditorInvestVC.borrowCode = self.detaiModel.borrow_code;
    [self.navigationController pushViewController:creditorInvestVC animated:YES];
}

- (void)loadUserInfo {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            
            weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
            
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

#pragma mark -没有登录，跳转到登录页面

- (void)goToLoginVC {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    UINavigationController *naviVC = [storyboard instantiateInitialViewController];
    
    [self presentViewController:naviVC animated:YES completion:^{
        
    }];
}

#pragma mark - BottomViewController delegate

- (void)describleBottomViewDidEndDragging:(UITableView *)bottomTableView {
    if (bottomTableView.contentOffset.y <= -40) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"showInvestButton" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@0];
    }
}

- (void)recordBottomViewDidEndDragging:(UITableView *)bottomTableView {
    if (bottomTableView.contentOffset.y <= -40) {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"showInvestButton" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@0];
    }
}

-(void)tenderInfoRecordBottomViewDidEndDragging:(UITableView *)bottomTableView {
    if (bottomTableView.contentOffset.y <= -40) {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"showInvestButton" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@0];
    }
}

-(void)transferRecordRecordBottomViewDidEndDragging:(UITableView *)bottomTableView {
    if (bottomTableView.contentOffset.y <= -40) {
         [[NSNotificationCenter defaultCenter] postNotificationName:@"showInvestButton" object:nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"scroll_up_or_down" object:@0];
        
    }
}

#pragma mark - 配置左右列表

//配置左右切换的列表VC
- (void)initialPageViewControllers {
    //配置所有两个列表的VC
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Finance" bundle:nil];
    MNDFinanceDescribleViewController *firstVC = [storyboard instantiateViewControllerWithIdentifier:[MNDFinanceDescribleViewController description]];
    firstVC.isCreditor = YES;
    MNDFinanceRecordViewController *secondVC = [storyboard instantiateViewControllerWithIdentifier:[MNDFinanceRecordViewController description]];
    MNDTenderInfoViewController *thirdVC = [storyboard instantiateViewControllerWithIdentifier:[MNDTenderInfoViewController description]];
    MNDTransferRecordViewController *forthVC = [storyboard instantiateViewControllerWithIdentifier:[MNDTransferRecordViewController description]];
    
    firstVC.delegate = self;
    secondVC.delegate = self;
    thirdVC.delegate = self;
    forthVC.delegate = self;
    
    self.describleVC = firstVC;
    self.financeRecordVC = secondVC;
    self.tenderInfoVC = thirdVC;
    self.transferRecordVC = forthVC;
    self.pageContentControllers = [NSMutableArray array];
    //将controller加入数组中
    [self.pageContentControllers addObject:firstVC];
    [self.pageContentControllers addObject:secondVC];
    [self.pageContentControllers addObject:thirdVC];
    [self.pageContentControllers addObject:forthVC];
    
    //把ContainerViewController变成PageViewController
    self.pageViewController = self.childViewControllers[0];
    self.pageViewController.dataSource = self;
    self.pageViewController.delegate = self;
    [self.pageViewController setViewControllers:@[self.pageContentControllers.firstObject]
                                      direction:UIPageViewControllerNavigationDirectionForward
                                       animated:YES
                                     completion:^(BOOL finished) {
                                         
                                     }];
    for (UIView *subView in self.pageViewController.view.subviews) {
        if ([subView isKindOfClass:[UIScrollView class]]) {
            ((UIScrollView *)subView).delegate = self;
        }
    }
}


#pragma mark - 跳转

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController {
    
    for (NSInteger i = 0; i < self.pageContentControllers.count - 1; i++) {
        if (viewController == [self.pageContentControllers objectAtIndex:i]) {
            return [self.pageContentControllers objectAtIndex:i + 1];
        }
    }
    return nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController {
    for (NSInteger i = self.pageContentControllers.count - 1; i > 0; i--) {
        if (viewController == [self.pageContentControllers objectAtIndex:i]) {
            
            return [self.pageContentControllers objectAtIndex:i - 1];
        }
    }
    return nil;
}


#pragma mark - UIPageViewControllerDelegate

- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers {
    
    if (pendingViewControllers.count > 0) {
        self.nextIndexController = [self checkIndexOfController:[pendingViewControllers firstObject]];
    }
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed {
    if (completed) {
        if (self.nextIndexController != -1) {
            self.currentIndexController = self.nextIndexController;
        }
        self.changedController = YES;
    }
    if (finished) {
        
    }
}

#pragma mark - UIScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.isTracking || scrollView.isDecelerating) {
        self.userDraggingStartedTransitionInProgress = YES;
    }
    
    CGPoint point = scrollView.contentOffset;
    
    float percentComplete;
    percentComplete = fabs(point.x - self.view.frame.size.width)/self.view.frame.size.width;
    
    if (self.isManuallSegmentSelect) {
        
        if (percentComplete == 1.0) {
            self.isGotoRighPlace = YES;
            self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.nextIndexController;
        }
        
        if (!self.isGotoRighPlace) {
            NSInteger changeIndex;
            if (self.nextIndexController > self.currentIndexController) {
                changeIndex = self.nextIndexController - self.currentIndexController;
            } else {
                changeIndex = self.currentIndexController - self.nextIndexController;
            }
            
            if (self.nextIndexController > self.currentIndexController || self.nextIndexController == self.pageContentControllers.count - 1) {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete * changeIndex  + self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            } else {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController - self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete * changeIndex;
            }
        }
    } else {
        CGFloat widthSegment = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count;
        
        if (percentComplete * widthSegment > widthSegment / 2) {
            [self changeSelectedButtonToIndex:self.nextIndexController];
        }
        
        if (self.changedController) {
            self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            self.changedController = NO;
        } else  {
            if (self.nextIndexController > self.currentIndexController || self.nextIndexController == self.pageContentControllers.count - 1) {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete + self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController;
            } else {
                self.indicatorLeadingConstraint.constant = self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * self.currentIndexController - self.indicatorContainerView.frame.size.width / self.pageContentControllers.count * percentComplete;
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.userDraggingStartedTransitionInProgress = NO;
}

#pragma mark - Action
//需要在storyboard设置button的tag值，或者在viewDidLoad设置
- (IBAction)tappSegmentAction:(UIButton *)sender {
    NSInteger index = sender.tag % 100;
    if (self.currentIndexController == index) {
        return;
    }
    
    if (self.userDraggingStartedTransitionInProgress) {
        return;
    }
    __weak typeof(self) weakSelf = self;
    UIPageViewControllerNavigationDirection direction;
    if (index > self.currentIndexController) {
        direction = UIPageViewControllerNavigationDirectionForward;
    }else{
        direction = UIPageViewControllerNavigationDirectionReverse;
    }
    
    self.isManuallSegmentSelect = YES;
    self.nextIndexController = index;
    
    id controller = self.pageContentControllers[index];
    NSArray *viewControllers = @[controller];
    [self.pageViewController setViewControllers:viewControllers direction:direction animated:YES completion:^(BOOL finished) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.currentIndexController = weakSelf.nextIndexController;
            [weakSelf changeSelectedButtonToIndex:weakSelf.currentIndexController];
            weakSelf.isGotoRighPlace = NO;
            weakSelf.isManuallSegmentSelect = NO;
        });
    }];
}

#pragma mark - Utility

- (NSInteger)checkIndexOfController:(UIViewController *)controller  {
    for (NSInteger i = 0; i < self.pageContentControllers.count; i++) {
        if (controller == [self.pageContentControllers objectAtIndex:i]) {
            return i;
        }
    }
    
    return -1;
}

- (void)changeSelectedButtonToIndex:(NSInteger)index {
    for (UIButton *button in self.segmentButtons) {
        if (button == [self.segmentButtons objectAtIndex:index]) {
            [button setSelected:YES];
        } else {
            [button setSelected:NO];
        }
    }
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
